package com.lj.back.manage.scaffold.module.kaptcha.service.impl;

import com.lj.back.manage.scaffold.common.enums.ResponseEnum;
import com.lj.back.manage.scaffold.config.RedisConfig;
import com.lj.back.manage.scaffold.module.kaptcha.service.KaptchaService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Priority;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 基于redis实现图形验证码service类
 * @author lv
 * @version 1.0.0
 */
@Service
@ConditionalOnBean({RedisConfig.class})
@Priority(1)
@AllArgsConstructor
public class RedisKaptchaServiceImpl implements KaptchaService {

    private final ValueOperations valueOperations;

    private final RedisTemplate redisTemplate;

    @Override
    public boolean record(String key, String code, long expireTime) {
        redisTemplate.opsForValue().set(key,code,expireTime, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public ResponseEnum valid(String key, String code) {
        String codeByRedis = getCode(key);
        if (StringUtils.isBlank(codeByRedis)){
            return ResponseEnum.CODE_GRAPH_INVALID;
        }
        if (!Objects.equals(code,codeByRedis)){
            return ResponseEnum.CODE_GRAPH_ERROR;
        }
        return ResponseEnum.SUCCESS;
    }

    @Override
    public boolean delete(String key) {
        redisTemplate.delete(key);
        return true;
    }

    @Override
    public String getCode(String key) {
        Object codeByRedis = valueOperations.get(key);
        if (codeByRedis == null){
            return null;
        }
        delete(key);
        return codeByRedis.toString();
    }
}
